package com.hsnn.medstgmini.trading.pur.dao.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.model.Status;
import com.hsnn.medstgmini.model.Whether;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.sys.model.UserType;
import com.hsnn.medstgmini.trading.pur.dao.AddressDao;
import com.hsnn.medstgmini.trading.pur.model.HospAddress;
import com.hsnn.medstgmini.util.Pagination;

/**
 * @category 医疗机构收货地址管理
 * @author 蔡春龙
 * @date 2015年7月8日
 */
@Repository
public class AddressDaoImpl implements AddressDao {

	@Resource(name = "sessionFactory")
	private SessionFactory factory;
	@Autowired
	private HibernateSqlUtil dao;

	/**
	 * @category 分页查询地址列表
	 * @date 2015年7月8日
	 * @param address
	 * @param page
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Pagination getAddressList(HospAddress address, Pagination page,
			SysUser user) {
		Session session = factory.getCurrentSession();
		Criteria criteria = session.createCriteria(HospAddress.class);

		if (user.getMain() == Whether.yes.getKey()) {
			criteria.add(Restrictions.eq("hospId", user.getOrgId()));
		} else {
			SysUser root = user.getRootUser();
			criteria.add(Restrictions.eq("hospId", root.getOrgId()));
			criteria.add(Restrictions.eq("user.id", user.getId()));
		}

		if (address != null) {
			String recpAddr = address.getRecpAddr();
			if (StringUtils.isNotBlank(recpAddr)) {
				criteria.add(Restrictions.like("recpAddr", recpAddr,
						MatchMode.ANYWHERE));
			}
			String recpUser = address.getRecpUser();
			if (StringUtils.isNotBlank(recpUser)) {
				criteria.add(Restrictions.like("recpUser", recpUser,
						MatchMode.ANYWHERE));
			}
			Integer status = address.getStatus();
			if (status != null) {
				criteria.add(Restrictions.eq("status", status));
			}
			SysUser sysUser = address.getUser();
			if (sysUser != null) {
				String name = sysUser.getName();
				if (StringUtils.isNotBlank(name)) {
					Criteria temp = criteria.createCriteria("user");
					temp.add(Restrictions
							.like("name", name, MatchMode.ANYWHERE));
				}
			}
		}

		// 查询个数
		criteria.setProjection(Projections.rowCount());
		Long records = (Long) criteria.uniqueResult();
		page.setRecords(records);

		// 查询列表
		criteria.setProjection(null);
		criteria.addOrder(Order.asc("user"));
		criteria.setFirstResult(page.getFirstResult());
		criteria.setMaxResults(page.getMaxResults());
		List<HospAddress> list = criteria.list();
		page.setRows(list);

		return page;
	}

	/**
	 * @category 根据id查询地址
	 * @date 2015年7月8日
	 * @param id
	 * @return
	 */
	@SuppressWarnings({ "unchecked" })
	public HospAddress getAddressById(String id) {
		Session session = factory.getCurrentSession();
		Criteria criteria = session.createCriteria(HospAddress.class);
		if (StringUtils.isNotBlank(id)) {
			criteria.add(Restrictions.eq("recpAddrId", id));
			List<HospAddress> list = criteria.list();
			if (list != null && !list.isEmpty()) {
				return list.get(0);
			}
		}
		return null;
	}
	
	public HospAddress getAddressByHospId(String hospId){
		Session session = factory.getCurrentSession();
		Criteria criteria = session.createCriteria(HospAddress.class);
		if (StringUtils.isNotBlank(hospId)) {
			criteria.add(Restrictions.eq("hospId", hospId));
			List<HospAddress> list = criteria.list();
			if (list != null && !list.isEmpty()) {
				return list.get(0);
			}
		}
		return null;
	}

	/**
	 * @category 保存地址
	 * @date 2015年7月8日
	 * @param address
	 */
	public void saveAddress(HospAddress address) {
		Session session = factory.getCurrentSession();
		if (address != null) {
			String id = address.getRecpAddrId();
			if (StringUtils.isBlank(id)) {
				address.setRecpAddrId(UUID.randomUUID().toString());
			}
			Integer isdefault = address.getIsdefault();
			if (isdefault == null) {
				isdefault = Whether.no.getKey();
				address.setIsdefault(isdefault);
			}
			session.saveOrUpdate(address);
			session.flush();
			if (isdefault == Whether.yes.getKey()) {
				setDefaultAddress(address);
			}
		}
	}

	/**
	 * @category 批量(启用|停用)
	 * @param list
	 */
	public void batchChangeStatus(List<HospAddress> list) {
		if (list != null && list.size() > 0) {
			for (HospAddress address : list) {
				changeStatus(address);
			}
		}
	}

	/**
	 * @category 启用|停用
	 * @param role
	 */
	public void changeStatus(HospAddress address) {
		Session session = factory.getCurrentSession();
		if (address != null) {
			HospAddress ha = getAddressById(address.getRecpAddrId());
			if (ha != null) {
				ha.setStatus(address.getStatus());
				ha.setUpdUser(address.getUpdUser());
				ha.setUpdDateTime(new Date());
				session.update(ha);
				session.flush();
			}
		}
	}

	/**
	 * @category 设置默认地址
	 * @date 2015年7月8日
	 * @param address
	 */
	public void setDefaultAddress(HospAddress address) {
		Session session = factory.getCurrentSession();
		if (address != null) {
			HospAddress ha = getAddressById(address.getRecpAddrId());
			if (ha != null) {
				String hospId = ha.getHospId();
				SysUser user = ha.getUser();
				if (user != null) {
					String userId = user.getId();
					if (StringUtils.isNotBlank(hospId)
							&& StringUtils.isNotBlank(userId)) {
						// 同一用户下的地址重置为非默认地址
						StringBuffer sb = new StringBuffer();
						sb.append("update pur_hospaddress set ");
						sb.append("isdefault = 0 ");
						sb.append(", upd_user = :updUser ");
						sb.append(", upd_datetime = :updDateTime ");
						sb.append("where 1 = 1 ");
						sb.append("and hosp_id = :hospId ");
						sb.append("and user_id = :userId ");
						SQLQuery query = session.createSQLQuery(sb.toString());
						query.setString("updUser", address.getUpdUser());
						query.setDate("updDateTime", new Date());
						query.setString("hospId", hospId);
						query.setString("userId", userId);
						query.executeUpdate();

						// 重新设置新默认地址
						ha.setIsdefault(Whether.yes.getKey());
						ha.setUpdUser(address.getUpdUser());
						ha.setUpdDateTime(new Date());
						session.update(ha);
					}
				}
				session.flush();
			}
		}
	}

	/**
	 * @category date 2015年7月8日
	 * @param user
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Pagination getUserList(SysUser user, Pagination page) {
		Session session = factory.getCurrentSession();
		if (user.getMain() == Whether.yes.getKey()) {
			Criteria criteria = session.createCriteria(SysUser.class);
			criteria.add(Restrictions.eq("status", Status.enabled.getKey()));
			criteria.add(Restrictions.eq("type", UserType.yy.getKey()));
			criteria.add(Restrictions.or(Restrictions.eq("pid", user.getId()),
					Restrictions.eq("id", user.getId())));

			// 查询条件
			String username = user.getUsername();
			if (StringUtils.isNotBlank(username)) {
				criteria.add(Restrictions.like("username", username,
						MatchMode.ANYWHERE));
			}
			String name = user.getName();
			if (StringUtils.isNotBlank(name)) {
				criteria.add(Restrictions
						.like("name", name, MatchMode.ANYWHERE));
			}

			// 查询个数
			criteria.setProjection(Projections.rowCount());
			Long records = (Long) criteria.uniqueResult();
			page.setRecords(records);

			// 查询列表
			criteria.setProjection(null);
			criteria.addOrder(Order.asc("pid"));
			criteria.addOrder(Order.desc("updDateTime"));
			criteria.setFirstResult(page.getFirstResult());
			criteria.setMaxResults(page.getMaxResults());
			List<HospAddress> list = criteria.list();
			page.setRows(list);
		}
		return page;
	}

	/**
	 * @category 查询用户默认地址
	 * @date 2015年7月9日
	 * @param user
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public HospAddress getDefaultAddress(SysUser user) {
		Session session = factory.getCurrentSession();
		Criteria criteria = session.createCriteria(HospAddress.class);
		if (user.getMain() == Whether.yes.getKey()) {
			criteria.add(Restrictions.eq("hospId", user.getOrgId()));
		} else {
			SysUser root = user.getRootUser();
			criteria.add(Restrictions.eq("hospId", root.getOrgId()));
		}
		criteria.add(Restrictions.eq("user.id", user.getId()));
		criteria.add(Restrictions.eq("status", Status.enabled.getKey()));
		criteria.add(Restrictions.eq("isdefault", Whether.yes.getKey()));

		List<HospAddress> list = criteria.list();
		if (list != null && !list.isEmpty()) {
			return list.get(0);
		}

		return null;
	}

}
